//
//  HomeCategoryVC.m
//  yunyan
//
//  Created by haichuang on 2018/2/24.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "HomeCategoryVC.h"
#import "HomeNewsCell.h"
#import "NewsHeaderView.h"
#import "NewsDetailsViewController.h"
#import "SHNesHomeTableViewCell.h"
@interface HomeCategoryVC () <UITableViewDelegate, UITableViewDataSource>{
    
    int page;
    
    NSMutableArray * _dataArray;
 
    
    NSString * typeStr;
    
}
@property (nonatomic, strong) UITableView * categoryTab;
//@property (nonatomic, strong) NSString *navTitle;
@end

@implementation HomeCategoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    typeStr = @"hot";
    page = 1;
    _dataArray = @[].mutableCopy;
    
    [self getMainListRequest];
   
    [self customNaviItemTitle:_navTitle isLeft:YES];
    
    self.categoryTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    [self.view addSubview:self.categoryTab];
    WeakSelf;

        [_categoryTab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.equalTo (weakSelf.view);

          
        }];

    
    
    self.categoryTab.delegate = self;
    self.categoryTab.dataSource = self;
    UIView * view = [[UIView alloc]init];
    self.categoryTab.tableFooterView = view;
    
    [self.categoryTab registerNib:[UINib nibWithNibName:@"HomeNewsCell" bundle:nil] forCellReuseIdentifier:@"HomeNewsCell"];
    
     [self.categoryTab registerNib:[UINib nibWithNibName:@"SHNesHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"SHNesHomeTableViewCell"];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        page =1;
        [self getMainListRequest];
        
    }];
    self.categoryTab.mj_header =header;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NewsHeaderView * headerView = [[NewsHeaderView alloc] init];

    if ([typeStr isEqualToString:@"hot"]) {
        
        [headerView.hotBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [headerView.commentBtn setTitleColor:RGBA(153, 153, 153, 1) forState:UIControlStateNormal];
    }else{
        [headerView.hotBtn setTitleColor:RGBA(153, 153, 153, 1) forState:UIControlStateNormal];
        [headerView.commentBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }
    
    headerView.hotBtnBlock =  ^(void){
        
        typeStr = @"hot";
        page = 1;
        [self getMainListRequest];
        NSLog(@"点击热门Btn");
    };
    
    headerView.commentBtnBlock = ^(void){
        
        typeStr = @"comment";
        page = 1;
        [self getMainListRequest];
        NSLog(@"点击评论Btn");
    };
    
    
    return headerView;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 84./2.;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.row];
    
    NSArray * imageArray = dic[@"cover_pic"];
    
    if (imageArray.count!=1) {
        
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, WIDTH -20, 20)];
        titleLabel.text = dic[@"title"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.numberOfLines = 2;
        [titleLabel sizeToFit];
        
        CGFloat widthImage = (WIDTH -40)/3;
        UIImageView * image;
        if (imageArray.count==0) {
            
            image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
        }else {
            
            for (int i = 0; i<imageArray.count; i++) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                image.layer.cornerRadius = 3.f;
                image.layer.masksToBounds = YES;
                
            }
            
        }
        
        return CGRectGetMaxY(image.frame)+40;
        
    }else{
        
        return 100.0f;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    NSDictionary * dic = _dataArray[indexPath.row];
    
//    HomeNewsCell * cell = [tableView dequeueReusableCellWithIdentifier:@"HomeNewsCell" forIndexPath:indexPath];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    [cell.newsImage sd_setImageWithURL:ImageUrl(dic[@"cover_pic"])];
//    cell.newsImage.layer.cornerRadius = 3.f;
//    cell.newsImage.layer.masksToBounds = YES;
//    cell.commentLabel.text = [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
//    cell.newsTitle.text  = dic[@"title"];
//    cell.timeLabel.text = [NSString stringWithFormat:@"%ld  %@",[dic[@"view_num"] integerValue],dic[@"create_time"]];
//    [cell setViewBottomShadow];
//    return cell;
    NSArray * imageArray = dic[@"cover_pic"];
    
    if (imageArray.count!=1) {
        
        static NSString * cellid = @"cellNews";
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellid];
        }else {
            
            while ([cell.contentView.subviews lastObject] !=nil) {
                
                [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
            }
        }
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, WIDTH -20, 20)];
        titleLabel.text = dic[@"title"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.numberOfLines = 2;
        [titleLabel sizeToFit];
        
        [cell.contentView addSubview:titleLabel];
        CGFloat widthImage = (WIDTH -40)/3;
        UIImageView * image;
        
        
        
        if (imageArray.count==0) {
            
            image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
        }else {
            
            for (int i = 0; i<imageArray.count; i++) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                image.layer.cornerRadius = 3.f;
                image.layer.masksToBounds = YES;
                [cell.contentView addSubview:image];
            }
            
        }
        
        UIImageView * messageView  =[[UIImageView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(image.frame)+10, 18, 18)];
        messageView.image = ImageName(@"home_comment_default");
        [cell.contentView addSubview:messageView];
        
        UILabel * comment = [[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(image.frame)+10, 50, 18)];
        comment.font = [UIFont systemFontOfSize:13];
        comment.text= [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
        comment.textColor  = [UIColor lightGrayColor];
        comment .numberOfLines = 1;
        [comment sizeToFit];
        
        [cell.contentView addSubview:comment];
        
        UIImageView * lookView  =[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(comment.frame)+10, CGRectGetMaxY(image.frame)+10, 18, 18)];
        lookView.image = ImageName(@"home_watch_default");
        [cell.contentView addSubview:lookView];
        
        UILabel * look = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lookView.frame)+3, CGRectGetMaxY(image.frame)+10, 50, 18)];
        look.font = [UIFont systemFontOfSize:13];
        look.text= [NSString stringWithFormat:@"%ld",[dic[@"view_num"] integerValue]];
        look.textColor  = [UIColor lightGrayColor];
        look .numberOfLines = 1;
        [look sizeToFit];
        [cell.contentView addSubview:look];
        
        UILabel * time = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH -150, CGRectGetMaxY(image.frame)+10, 140, 18)];
        time.font = [UIFont systemFontOfSize:13];
        time.text= [NSString stringWithFormat:@"%@",dic[@"create_time"]];
        time.textColor  = [UIColor lightGrayColor];
        time.textAlignment = NSTextAlignmentRight;
        
        [cell.contentView addSubview:time];
        
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(time.frame)+10, WIDTH -20, 0.5)];
        lineView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
        [cell.contentView addSubview:lineView];
        return cell;
        
        
    }else {  // 单图
        SHNesHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SHNesHomeTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.image sd_setImageWithURL:ImageUrl(dic[@"cover_pic"][0])];
        
        if (ISP5||ISP4) {
            cell.image.frame = CGRectMake(10, (100 -((WIDTH -40)/3 * 0.7))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.7);
        }else {
            cell.image.frame = CGRectMake(10, (100 -((WIDTH -40)/3 * 0.6))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.6);
        }
        cell.image.layer.cornerRadius = 3.f;
        cell.image.layer.masksToBounds = YES;
        cell.commentNumber.text = [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
        
        if (ISP5||ISP4) {
            cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 15, WIDTH -((WIDTH -40)/3-5)-20, 20);
        }else{
            cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 12, WIDTH -((WIDTH -40)/3-5)-20, 20);
        }
        cell.titleLabel.text  = dic[@"title"];
        cell.titleLabel.numberOfLines = 2;
        [cell.titleLabel sizeToFit];
        
        cell.commentNumber.numberOfLines = 1;
        [cell.commentNumber sizeToFit];
        
        cell.commentImage.frame = CGRectMake((WIDTH -40)/3+20, 70, 18, 18);
        cell.commentNumber.frame  = CGRectMake((WIDTH -40)/3 + 40, 70, 18, 18);
        cell.lookImage.frame = CGRectMake(CGRectGetMaxX(cell.commentNumber.frame)+10, 70, 18, 18);
        
        
        cell.timeLabel.frame = CGRectMake(CGRectGetMaxX(cell.lookImage.frame)+3, 70, WIDTH - (CGRectGetMaxX(cell.lookImage.frame)+10), 18);
        
        if (ISP5||ISP4) {
            cell.time.hidden =YES;
            
            cell.timeLabel.text = [NSString stringWithFormat:@"%ld  %@",[dic[@"view_num"] integerValue],dic[@"create_time"]];
        }else {
            
            cell.timeLabel.text = [NSString stringWithFormat:@"%ld",[dic[@"view_num"] integerValue]];
            cell.time.frame =  CGRectMake(WIDTH -150, CGRectGetMaxY(cell.timeLabel.frame)-18, 140, 18);
            
            cell.time.text= [NSString stringWithFormat:@"%@",dic[@"create_time"]];
            
            cell.time.textAlignment = NSTextAlignmentRight;
            
        }
        
        UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(cell.contentView.frame)-0.5, WIDTH -20, 0.5)];
        lineView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
        [cell.contentView addSubview:lineView];
        
        [cell setViewBottomShadow];
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
      NSDictionary * dic = _dataArray[indexPath.row];
    NewsDetailsViewController * homeDetiel = [[NewsDetailsViewController alloc]init];
    homeDetiel.news_idStr = [NSString stringWithFormat:@"%ld",[dic[@"id"] integerValue]];
    //        homeDetiel.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:homeDetiel animated:YES];
}

-(void)getMainListRequest{
    
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                           @"class_id":self.classID
                           };
    
    if ([typeStr isEqualToString:@"hot"]) {
        dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                @"class_id":self.classID,
                @"hot":@"DESC"
                };
    }else{
        
        dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                @"class_id":self.classID,
                @"comment":@"DESC"
                };
    }
    [PostNetWorking postNetWorkingStr:RequestUrlStr(news_list_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }
            [self.categoryTab reloadData];
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"msg"]);
        }
        
        [self.categoryTab.mj_header endRefreshing];
        [self.categoryTab.mj_footer endRefreshing];
        NSLog(@"responseObject = %@",responseObject);
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
        
        [self.categoryTab.mj_header endRefreshing];
        [self.categoryTab.mj_footer endRefreshing];
        
    }];
    
}


@end
